/**
 * 商品列表页面组件
 * 
 * 功能说明：
 * - 展示商品列表，支持多条件筛选和搜索
 * - 提供商品分类、成色、价格等筛选条件
 * - 支持按价格、发布时间等排序
 * - 展示商品基本信息，包括图片、名称、价格、成色等
 * - 支持商品收藏功能（登录用户）
 * - 支持分页浏览商品
 */

import React, { useState, useEffect } from 'react'
import { 
  Card, 
  Row, 
  Col, 
  Input, 
  Select, 
  Button, 
  Pagination, 
  message, 
  Empty, 
  Tag, 
  Divider,
  Skeleton,
  Space,
  Badge,
  Modal, // 引入Ant Design Modal组件
  Avatar, // 引入Ant Design Avatar组件
  Tooltip // 引入Ant Design Tooltip组件
} from 'antd'
import { 
  SearchOutlined, 
  HeartOutlined, 
  HeartFilled, 
  EyeOutlined,
  ShoppingCartOutlined 
} from '@ant-design/icons'
import { useAuthStore } from '@stores/auth'
import { useNavigate } from 'react-router-dom'
import apiClient from '../services/api'
import dayjs from 'dayjs' // 引入dayjs用于日期格式化

const { Option } = Select
const { Meta } = Card

// 商品成色映射
// 将数据库中的成色代码映射为显示文本和颜色
const CONDITION_MAP = {
  new: { text: '全新', color: 'green' },
  like_new: { text: '几乎全新', color: 'blue' },
  good: { text: '良好', color: 'cyan' },
  fair: { text: '一般', color: 'orange' },
  poor: { text: '较差', color: 'red' }
}

// 在文件顶部插入全局样式（用JSX方式）
const recommendModalStyle = `
@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.96); }
  to { opacity: 1; transform: scale(1); }
}
@keyframes fadeOut {
  from { opacity: 1; transform: scale(1); }
  to { opacity: 0; transform: scale(0.96); }
}
.recommend-img-hover:hover {
  transform: scale(1.08);
  box-shadow: 0 4px 24px #bbb;
  z-index: 2;
}
`;

/**
 * 商品列表页面组件
 * 
 * @returns {JSX.Element} 商品列表页面元素
 */
function ProductListPage() {
  const { isAuthenticated, user } = useAuthStore()
  const navigate = useNavigate()

  // 状态管理
  const [loading, setLoading] = useState(true)           // 加载状态
  const [products, setProducts] = useState([])           // 商品列表
  const [categories, setCategories] = useState([])       // 商品分类列表
  const [favorites, setFavorites] = useState(new Set())  // 用户收藏集合
  const [pagination, setPagination] = useState({         // 分页信息
    current: 1,
    pageSize: 12,
    total: 0
  })

  // 搜索和筛选状态
  const [searchParams, setSearchParams] = useState({
    keyword: '',            // 搜索关键词
    category_id: '',        // 分类ID
    condition_rating: '',   // 成色等级
    min_price: '',          // 最低价格
    max_price: '',          // 最高价格
    sort: 'created_at',     // 排序字段
    order: 'DESC'           // 排序方向
  })

  // 推荐商品弹窗相关状态
  const [recommend, setRecommend] = useState(null)
  const [modalVisible, setModalVisible] = useState(false)

  // 组件挂载时加载分类数据
  useEffect(() => {
    fetchCategories()
  }, [])

  // 在组件挂载时插入全局样式
  useEffect(() => {
    if (!document.getElementById('recommend-modal-style')) {
      const style = document.createElement('style');
      style.id = 'recommend-modal-style';
      style.innerHTML = recommendModalStyle;
      document.head.appendChild(style);
    }
  }, []);

  // 分页、搜索参数变化时加载商品数据
  useEffect(() => {
    fetchProducts()
  }, [pagination.current, pagination.pageSize, searchParams])

  // 用户认证状态变化时加载用户收藏
  useEffect(() => {
    if (isAuthenticated) {
      fetchUserFavorites()
    }
  }, [isAuthenticated])

  // 获取当前用户ID
  const recommendKey = user ? `recommend_shown_${user.id}` : 'recommend_shown';

  // 页面加载时请求推荐商品（只在本次登录本账号第一次进入商品市场时弹窗）
  useEffect(() => {
      if (!isAuthenticated || !user) return;
      
      const fetchRecommend = async () => {
        if (sessionStorage.getItem(recommendKey)) return;
        try {
          const res = await apiClient.get('/api/products/recommend', {
            params: { page: 1, size: 20 }
          });
          if (res.data && res.data.items && res.data.items.length > 0) {
            const idx = Math.floor(Math.random() * res.data.items.length);
            setRecommend(res.data.items[idx]);
            setModalVisible(true);
            sessionStorage.setItem(recommendKey, '1');
          }
        } catch (error) {
          console.error('获取推荐商品失败:', error);
        }
      };
      
      fetchRecommend();
    }, [isAuthenticated, user]);

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await apiClient.get('/api/products/categories')
      
      // 处理响应数据 - 后端返回 {status: "success", data: [...]}
      setCategories(Array.isArray(response.data.data) ? response.data.data : [])
      
    } catch (error) {
      console.error('获取分类列表失败:', error)
      message.error('获取分类列表失败')
    }
  }

  // 获取商品列表
  const fetchProducts = async () => {
    try {
      setLoading(true)
      const params = {
        page: pagination.current,
        limit: pagination.pageSize,
        ...searchParams
      }

      // 过滤掉空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })
      
      console.log('请求参数:', params)
      const response = await apiClient.get('/api/products', { params })
      
      // 处理响应数据 - 后端直接返回PaginatedResponse对象
      console.log('完整API响应:', JSON.stringify(response))
      console.log('响应状态:', response.status)
      console.log('响应数据:', response.data)
      
      // 直接从response.data获取数据
      const productItems = Array.isArray(response.data.items) ? response.data.items : []
      const totalCount = typeof response.data.total === 'number' ? response.data.total : 0
      
      console.log('解析后的商品数量:', productItems.length)
      console.log('解析后的总数:', totalCount)
      
      setProducts(productItems)
      setPagination(prev => ({
        ...prev,
        total: totalCount
      }))
      
      // 随机推荐逻辑
      if (productItems.length > 0) {
        const randomIndex = Math.floor(Math.random() * productItems.length)
        setRecommend(productItems[randomIndex])
      }
    } catch (error) {
      console.error('获取商品列表失败:', error)
      console.error('错误详情:', error.message)
      console.error('错误堆栈:', error.stack)
      message.error('获取商品列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 获取用户收藏列表
  const fetchUserFavorites = async () => {
    try {
      const response = await apiClient.get('/api/users/me/favorites')
      if (response.data?.status === 'success' && response.data.data?.favorites) {
        const favoriteIds = new Set(
          response.data.data.favorites.map(fav => fav.product_id)
        )
        setFavorites(favoriteIds)
      }
    } catch (error) {
      console.error('获取收藏列表失败:', error)
    }
  }

  // 处理搜索
  const handleSearch = (value) => {
    setSearchParams(prev => ({ ...prev, keyword: value }))
    setPagination(prev => ({ ...prev, current: 1 })) // 重置到第一页
  }

  // 处理筛选条件变化
  const handleFilterChange = (field, value) => {
    setSearchParams(prev => ({ ...prev, [field]: value }))
    setPagination(prev => ({ ...prev, current: 1 })) // 重置到第一页
  }

  // 处理排序变化
  const handleSortChange = (value) => {
    // 只允许合法的排序组合
    const ALLOWED = [
      'created_at_DESC',
      'created_at_ASC',
      'price_ASC',
      'price_DESC',
      'view_count_DESC'
    ];
    if (!ALLOWED.includes(value)) return;
    const [sort, order] = value.split('_');
    setSearchParams(prev => ({ ...prev, sort, order }));
    setPagination(prev => ({ ...prev, current: 1 }));
  }

  // 处理分页变化
  const handlePageChange = (page, pageSize) => {
    setPagination(prev => ({ ...prev, current: page, pageSize }))
  }

  // 处理商品收藏/取消收藏
  const handleFavorite = async (productId) => {
    if (!isAuthenticated) {
      message.info('请先登录')
      return
    }

    try {
      const isFavorited = favorites.has(productId)
      
      if (isFavorited) {
        // 取消收藏
        await apiClient.delete(`/api/products/${productId}/favorite`)
        setFavorites(prev => {
          const newSet = new Set(prev)
          newSet.delete(productId)
          return newSet
        })
        message.success('取消收藏成功')
      } else {
        // 添加收藏
        await apiClient.post(`/api/products/${productId}/favorite`)
        setFavorites(prev => new Set([...prev, productId]))
        message.success('收藏成功')
      }
    } catch (error) {
      console.error('收藏操作失败:', error)
      message.error('收藏操作失败')
    }
  }

  // 跳转到商品详情页
  const handleViewProduct = (productId) => {
    navigate(`/products/${productId}`)
  }

  // 清空所有筛选条件
  const handleClearFilters = () => {
    setSearchParams({
      keyword: '',
      category_id: '',
      condition_rating: '',
      min_price: '',
      max_price: '',
      sort: 'created_at',
      order: 'DESC'
    })
    setPagination(prev => ({ ...prev, current: 1 }))
  }

  // 商品卡片组件
  const ProductCard = ({ product }) => (
    <Card
      hoverable
      className="product-card"
      style={{ minHeight: '420px', height: '420px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative' }}
      cover={
        <div className="product-image" style={{ position: 'relative' }}>
          <img
            alt={product.title}
            src={
              // 优先使用 images 数组，否则使用 images_rel 关系
              (product.images && product.images.length > 0 && typeof product.images[0] === 'string')
                ? (product.images[0].startsWith('/uploads/')
                    ? product.images[0]
                    : `/uploads/${product.images[0].replace(/^uploads\//, '')}`)
                : (product.images_rel && product.images_rel[0] && product.images_rel[0].image_url)
                ? (product.images_rel[0].image_url.startsWith('/uploads/')
                    ? product.images_rel[0].image_url
                    : `/uploads/${product.images_rel[0].image_url.replace(/^uploads\//, '')}`)
                : 'https://via.placeholder.com/300x200?text=No+Image'
            }
            style={{ width: '100%', height: '200px', objectFit: 'cover' }}
          />
          {isAuthenticated && (
            // 收藏按钮，登录用户可见
            <Button
              type="text"
              shape="circle"
              size="small"
              icon={favorites.has(product.id) ? <HeartFilled /> : <HeartOutlined />}
              onClick={(e) => {
                e.stopPropagation()
                handleFavorite(product.id)
              }}
              style={{
                position: 'absolute',
                top: '8px',
                right: '8px',
                background: 'rgba(255, 255, 255, 0.8)',
                color: favorites.has(product.id) ? '#ff4d4f' : '#666'
              }}
            />
          )}
        </div>
      }
      styles={{ body: { flex: 1, display: 'flex', flexDirection: 'column', paddingBottom: 56 } }} // 预留底部操作栏高度
    >
      <Meta
        title={
          <div>
            {product.title}
            {/* 成色标签 */}
            <Tag 
              color={CONDITION_MAP[product.condition_rating]?.color} 
              style={{ marginLeft: '8px' }}
            >
              {CONDITION_MAP[product.condition_rating]?.text}
            </Tag>
          </div>
        }
        description={
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 60 }}>
            {/* 商品描述，截断显示，最多2行省略号 */}
            <div style={{ marginBottom: '8px', flex: 1, maxHeight: 44, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', color: '#444', fontSize: 15 }}>
              {product.description}
            </div>
            {/* 底部信息：卖家和浏览量 */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 'auto' }}>
              <span style={{ color: '#666' }}>
                {product.user?.nickname || product.user?.username || '匿名用户'}
              </span>
              <Space>
                <Badge count={product.view_count || 0} showZero color="#108ee9" />
                <EyeOutlined style={{ color: '#666' }} />
              </Space>
            </div>
          </div>
        }
      />
      {/* 固定底部操作栏，始终对齐底部 */}
      <div style={{
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        background: '#fff',
        borderTop: '1px solid #f0f0f0',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '8px 16px',
        zIndex: 2
      }}>
        <div style={{ color: '#ff4d4f', fontSize: '18px', fontWeight: 'bold' }}>
          ¥{product.price}
        </div>
        <Button 
          type="primary" 
          icon={<EyeOutlined />}
          onClick={() => handleViewProduct(product.id)}
          style={{ borderRadius: 16, fontWeight: 600 }}
        >
          查看详情
        </Button>
      </div>
    </Card>
  )

  // 修正分页参数，防止显示异常
  const realTotal = pagination.total > 0 ? pagination.total : products.length
  const realCurrent = pagination.current || 1
  const realPageSize = pagination.pageSize || 12

  // 推荐弹窗图片优先级：images[0] > images_rel[0] > 占位图
  const getRecommendImage = (recommend) => {
    // 优先用 images[0]
    if (recommend.images && recommend.images.length > 0 && typeof recommend.images[0] === 'string') {
      const url = recommend.images[0];
      if (url.startsWith('/uploads/')) return url;
      if (url.startsWith('uploads/')) return '/' + url;
      return `/uploads/${url.replace(/^uploads[\\/]*/, '')}`;
    }
    // 其次用 images_rel[0]
    if (recommend.images_rel && recommend.images_rel.length > 0 && recommend.images_rel[0].image_url) {
      const url = recommend.images_rel[0].image_url;
      if (url.startsWith('/uploads/')) return url;
      if (url.startsWith('uploads/')) return '/' + url;
      return `/uploads/${url.replace(/^uploads[\\/]*/, '')}`;
    }
    // 都没有则用占位图
    return 'https://via.placeholder.com/300x200?text=No+Image';
  };

  return (
    <div style={{ 
      marginTop: 64,
      marginLeft: isAuthenticated ? 200 : 0,
      minHeight: 'calc(100vh - 64px)',
      padding: '24px'
    }}>
      {/* 推荐商品弹窗 */}
      <Modal
        title={<span style={{ fontWeight: 700, fontSize: 20, letterSpacing: 2 }}>为你推荐</span>}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          recommend && <Button key="detail" type="primary" style={{ borderRadius: 20, fontWeight: 600, fontSize: 16, padding: '0 32px', boxShadow: '0 2px 8px #eee' }} onClick={() => { setModalVisible(false); handleViewProduct(recommend.id) }}>查看详情</Button>,
          <Button key="close" style={{ borderRadius: 20 }} onClick={() => setModalVisible(false)}>关闭</Button>
        ]}
        centered
        styles={{ body: { padding: 24, minHeight: 320, transition: 'opacity 0.3s' } }}
        maskStyle={{ background: 'rgba(0,0,0,0.25)', transition: 'opacity 0.3s' }}
        style={{ borderRadius: 16, animation: modalVisible ? 'fadeIn 0.4s' : 'fadeOut 0.4s' }}
        destroyOnClose
      >
        {recommend ? (
          <div style={{ textAlign: 'center', animation: modalVisible ? 'fadeIn 0.4s' : 'fadeOut 0.4s' }}>
            <div style={{ position: 'relative', display: 'inline-block', marginBottom: 16 }}>
              <img
                src={getRecommendImage(recommend)}
                alt={recommend.name}
                style={{ width: 260, height: 180, objectFit: 'cover', borderRadius: 10, boxShadow: '0 2px 12px #eee', transition: 'transform 0.3s', cursor: 'pointer', background: '#f5f5f5' }}
                className="recommend-img-hover"
                onError={e => { e.target.onerror = null; e.target.src = 'https://via.placeholder.com/300x200?text=No+Image'; }}
              />
            </div>
            <h3 style={{ fontWeight: 700, fontSize: 22, margin: '8px 0', color: '#222' }}>{recommend.name}</h3>
            <div style={{ marginBottom: 8 }}>
              <Tag color={CONDITION_MAP[recommend.condition_rating]?.color} style={{ fontSize: 15, padding: '2px 12px', borderRadius: 12, fontWeight: 600 }}>{CONDITION_MAP[recommend.condition_rating]?.text}</Tag>
              <Tag color="blue" style={{ fontSize: 15, padding: '2px 12px', borderRadius: 12, fontWeight: 600 }}>{recommend.Category?.name || '未分类'}</Tag>
            </div>
            <div style={{ color: '#ff4d4f', fontSize: 26, fontWeight: 800, marginBottom: 8, letterSpacing: 1 }}>￥{recommend.price}</div>
            <div style={{ color: '#666', marginBottom: 12, fontSize: 16 }}>{recommend.description?.length > 60 ? recommend.description.substring(0, 60) + '...' : recommend.description}</div>
            <div style={{ color: '#888', fontSize: 14, marginBottom: 8 }}>发布时间：{dayjs(recommend.created_at).format('YYYY-MM-DD HH:mm')}</div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 4 }}>
              <Avatar src={recommend.User?.avatar_url || undefined} style={{ marginRight: 8, background: '#eee' }} size={40} />
              <span style={{ fontWeight: 700, fontSize: 17, color: '#333' }}>{recommend.User?.nickname || recommend.User?.username || '匿名用户'}</span>
            </div>
          </div>
        ) : (
          <div style={{ textAlign: 'center', color: '#888', fontSize: 18, padding: 40 }}>
            暂无个性化推荐商品，快去浏览/收藏/购买你感兴趣的商品吧！
          </div>
        )}
      </Modal>
      {/* 搜索和筛选区域 */}
      <Card style={{ marginBottom: '24px' }}>
        <Row gutter={[16, 16]}>
  
          {/* 搜索框 */}
          <Col xs={24} sm={12} md={8}>
            <Input.Search
              placeholder="搜索商品..."
              value={searchParams.keyword}
              onChange={(e) => setSearchParams(prev => ({ ...prev, keyword: e.target.value }))}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
              size="large"
            />
          </Col>
          {/* 分类筛选 */}
          <Col xs={24} sm={12} md={4}>
            <Select
              placeholder="选择商品分类"
              value={searchParams.category_id}
              onChange={(value) => handleFilterChange('category_id', value)}
              style={{ width: '100%' }}
              size="large"
              allowClear
            >
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Col>
          {/* 成色筛选 */}
          <Col xs={24} sm={12} md={4}>
            <Select
              placeholder="选择商品成色"
              value={searchParams.condition_rating}
              onChange={(value) => handleFilterChange('condition_rating', value)}
              style={{ width: '100%' }}
              size="large"
              allowClear
            >
              {Object.entries(CONDITION_MAP).map(([key, { text }]) => (
                <Option key={key} value={key}>{text}</Option>
              ))}
            </Select>
          </Col>
          {/* 排序选择 */}
          <Col xs={24} sm={12} md={4}>
            <Select
              placeholder="排序方式"
              value={["created_at_DESC","created_at_ASC","price_ASC","price_DESC","view_count_DESC"].includes(`${searchParams.sort}_${searchParams.order}`) ? `${searchParams.sort}_${searchParams.order}` : "created_at_DESC"}
              onChange={value => {
                // 只允许合法的排序组合
                const ALLOWED = [
                  'created_at_DESC',
                  'price_ASC',
                  'price_DESC'
                ];
                if (!ALLOWED.includes(value)) return;
                const [sort, order] = value.split('_');
                setSearchParams(prev => ({ ...prev, sort, order }));
                setTimeout(() => setPagination(prev => ({ ...prev, current: 1 })), 0); // 强制同步
              }}
              style={{ width: '100%' }}
              size="large"
            >
              <Option value="created_at_DESC">最新发布</Option>
              <Option value="price_ASC">价格从低到高</Option>
              <Option value="price_DESC">价格从高到低</Option>
            </Select>
          </Col>
        </Row>
        
        {/* 价格范围筛选 */}
        <Divider />
        <Row gutter={[16, 16]} align="middle">
          <Col>
            <span>价格范围：</span>
          </Col>
          <Col>
            <Input
              placeholder="最低价"
              value={searchParams.min_price}
              onChange={(e) => setSearchParams(prev => ({ ...prev, min_price: e.target.value }))}
              style={{ width: '100px' }}
              prefix="¥"
            />
          </Col>
          <Col>
            <span>-</span>
          </Col>
          <Col>
            <Input
              placeholder="最高价"
              value={searchParams.max_price}
              onChange={(e) => setSearchParams(prev => ({ ...prev, max_price: e.target.value }))}
              style={{ width: '100px' }}
              prefix="¥"
            />
          </Col>
          <Col>
            <Button 
              type="primary" 
              onClick={() => setPagination(prev => ({ ...prev, current: 1 }))}
            >
              应用价格筛选
            </Button>
          </Col>
          <Col>
            <Button 
              onClick={handleClearFilters}
              style={{ width: '100%' }}
              size="large"
            >
              清空筛选
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 商品列表区域 */}
      {loading ? (
        // 加载中骨架屏
        <Row gutter={[16, 16]}>
          {Array.from({ length: 12 }).map((_, index) => (
            <Col xs={24} sm={12} md={8} lg={6} key={index}>
              <Card>
                <Skeleton loading active />
              </Card>
            </Col>
          ))}
        </Row>
      ) : products.length === 0 ? (
        // 无商品时显示空状态
        <Empty
          description="暂无商品"
          style={{ marginTop: '60px' }}
        />
      ) : (
        // 显示商品列表
        <>
          <Row gutter={[16, 16]}>
            {products.map(product => (
              <Col xs={24} sm={12} md={8} lg={6} key={product.id}>
                <ProductCard product={product} />
              </Col>
            ))}
          </Row>
          
          {/* 分页组件 */}
          <div className="pagination-bar">
            <Pagination
              current={pagination.current}
              pageSize={pagination.pageSize}
              total={pagination.total}
              onChange={handlePageChange}
              showSizeChanger
              showQuickJumper
              showTotal={(total, range) => {
                if (total === 0) return '暂无商品';
                return `第 ${range[0]}-${range[1]} 条，共 ${total} 条商品`;
              }}
              pageSizeOptions={['12', '24', '48', '96']}
            />
          </div>
        </>
      )}
    </div>
  )
}

export default ProductListPage 